<template>
  <div class="course_edit">
    <div class="flex mb10 flex_h_between">
      <div class="info_text cursor" @click="back"><a-icon type="left" />返回</div>
    </div>
    <a-form :form="form" layout="inline" class="form_wrap">
      <a-form-item label="名称" style="width: 100%;">
        <a-input v-decorator="['name',{rules: [{ required: true, message: `${$t('common.pleaseEnter')}名称` }]}]" placeholder="名称" />
      </a-form-item>
      <a-form-item label="作者" style="width: 100%;">
        <a-input v-decorator="['author',{rules: [{ required: true, message: `${$t('common.pleaseEnter')}作者` }]}]" placeholder="作者" />
      </a-form-item>
      <a-form-item label="上传照片" style="width: 100%;">
        <a-upload list-type="picture-card" :file-list="fileListPreview" :remove="handleRemove" :before-upload="beforeUpload" @preview="handlePreview" @change="handleChange">
          <div v-if="fileList.length < 1 && fileListPreview.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">
              上传
            </div>
          </div>
        </a-upload>
      </a-form-item>
      <a-row class="mt20 text_center">
        <a-form-item class="mt20 text_center">
          <a-button type="primary" @click="submit" style="width: 150px;height:40px;">提交</a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { createPic, picDetail } from '@/api/config'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  name: 'imgsEdit',
  components: { },
  data () {
    return {
      moment,
      form: this.$form.createForm(this),
      detail: {},
      fileList: [],
      fileListPreview: [],
      previewVisible: false,
      previewImage: ''
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  async mounted () {
    if (this.$route.query.id) {
      await this.getDetail()
      let detail = JSON.parse(JSON.stringify(this.detail))
      this.form.setFieldsValue(detail)
      this.$forceUpdate()
    }
  },
  watch: {
  },
  methods: {
    back () {
      this.$router.go(-1)
    },
    async getDetail () {
      let res = await picDetail({ id: this.$route.query.id })
      if (res.code === 200) {
        this.detail = res.data
        if (res.data.filePath) {
          this.fileListPreview = [{ uid: 1, name: res.data.fileName, status: 'done', url: '/sysFile/fileShow?url=' + res.data.filePath.replaceAll('\\', '/') }]
        }
      }
    },
    async createData (params) {
      let res = await createPic(params)
      if (res.code === 200) {
        this.$message.success('提交成功')
      } else {
        this.$message.error(res.message)
      }
    },
    async submit () {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          console.info(values)
          let valuesCopy = JSON.parse(JSON.stringify(values))
          const { fileList } = this
          const formData = new FormData()
          formData.append('file', fileList[0])
          if (this.$route.query.id) {
            formData.append('id', this.$route.query.id)
          }
          formData.append('name', valuesCopy.name)
          formData.append('author', valuesCopy.author)
          console.info(formData)
          await this.createData(formData)
          this.$router.push('/home/imgsManage')
        }
      })
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      this.fileList = [file]
      // const isLt2M = file.size / 1024 / 1024 < 10
      // if (!isLt2M) {
      //   this.$message.error('文件不能超过10MB!') // 限制文件的大小为不能超过10M
      // }
      // return isLt2M
      return false
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      this.fileListPreview = fileList
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.course_edit
  padding 20px 30px
  background #fff
  min-height calc(100vh - 107px)
  .course_edit_title
    text-align center
    font-size 16px
    font-weight bold
  .form_wrap
    // width: 900px;
    // margin: 0 auto;
    ::v-deep .ant-form-item
      width 100%
      margin-right 0
      margin-bottom 10px
    :deep(.ant-form-item-label)
      width 120px
    .ant-form-item-control-wrapper
      width 180px
    .ant-row
      min-width 300px
    .subject_wrap
      display: flex;
      align-items: center;
    ::v-deep .ant-form-item-control-wrapper
      width: calc(100% - 120px);
</style>
